"use strict";
var timeout;
var gProvinces;
var imageSrc = null;

app.controller("SystemUserController", ["$scope", "$modal", "$timeout", "RESTService", "ModeShapeService", "AuthService",
    function ($scope, $modal, $timeout, RESTService, ModeShapeService, AuthService) {
        //load user roles
        $scope.buttonClass = ["btn-default", "btn-primary", "btn-success", "btn-info", "btn-warning", "btn-danger", "btn-primary", "btn-success", "btn-info", "btn-warning", "btn-danger", "btn-primary", "btn-success", "btn-info", "btn-warning", "btn-danger"];
        $scope.userRoles = [];
        RESTService.getResponse("/rest/userrole/getFilterUserRoles?").then(function (response) {
            angular.forEach(response, function (value) {
                var disabled = "";
                if (value.key == "all") {
                    disabled = "disabled";
                }
                this.push({
                    key: value.key,
                    cnName: value.cnName,
                    enName: value.enName,
                    disabled: disabled
                });
            }, $scope.userRoles);
        });
        //load users
        $scope.userRole = "all";
        $scope.userLike = "";
        $scope.page = {
            totalItems: 0,
            currentPage: 1,
            currentItems: 0,
            maxSize: 5,				//max size of pagination
            itemsPerPage: 10
        }
        $scope.setPage = function (pageNo) {
            $scope.page.currentPage = pageNo;
        };
        $scope.pageChanged = function () {
            loadUserListData();
        };
        $scope.refreshUserListData = function (usrRole) {
            if (usrRole != null && usrRole != "") {
                $scope.userRole = usrRole;
            }
            $scope.setButtomDisabled(usrRole);
            loadUserListData();
        };
        $scope.setButtomDisabled = function (usrRole) {
            if (usrRole != null && usrRole != "") {
                angular.forEach($scope.userRoles, function (value) {
                    if (value.key == usrRole) {
                        value.disabled = "disabled";
                    } else {
                        value.disabled = "";
                    }
                })
            }
        }

        /*    $scope.$watch('userLike', function (newVal, oldVal) {
         if (newVal !== oldVal) {
         if (timeout) $timeout.cancel(timeout);
         timeout = $timeout(function() {
         $scope.refreshUserListData();
         }, 800);
         }
         }, true);*/

        $scope.users = [];


        var loadUserListData = function () {
            if ($scope.userRole == null) {
                $scope.userRole = "all";
            }
            console.log("2======$scope.userRole: ", $scope.userRole);
            console.log("2======$scope.userLike: ", $scope.userLike);
            console.log("2======$scope.page.currentPage: ", $scope.page.currentPage);
            RESTService.getResponse("/rest/user/getUsersCount?userRole=" + $scope.userRole + "&like=" + $scope.userLike).then(function (response) {
                $scope.page.totalItems = response[0].count;
            });
            RESTService.getResponse("/rest/user/getUsers?userRole=" + $scope.userRole + "&like=" + $scope.userLike + "&pageNo=" + $scope.page.currentPage + "&pageSize=" + $scope.page.itemsPerPage)
                .then(function (response) {
                    $scope.users = response;
                    $scope.page.currentItems = $scope.users.length;
                });
        }

        loadUserListData()

        $scope.init = function () {
            loadUserListData();
        }

        //3 open modal
        $scope.open = function (attrs, model) {
            model.scope = $scope;
            var modalInstance = $modal.open(angular.extend({
                backdrop: 'static',
                controller: "ModalInstanceCtrl",
                resolve: {
                    items: function () {
                        return [Object(model)];
                    }
                }
            }, attrs));
        };

    }]);

// app.controller("UserDetailCtrl", ["$scope", "RESTService",
//     function ($scope, RESTService) {
//         $scope.user = angular.extend({}, $scope.selected.item);
//
//         $scope.activityList = [];
//
//         if ($scope.user._doctor == null) {
//             $scope.user._doctor = {
//                 userId: '',
//                 doctQuali_Id: '',
//                 hosp_Id: '',
//                 dept_Id: '',
//                 doctor_Intro: '',
//                 fee_Recommend: 0,
//                 fee_Diag: 0,
//                 fee_Solution: 0,
//                 cost_Surgery: 0,
//                 fee_Surgery: 0
//             }
//         }
//
//         $scope.page = {
//             totalItems: 0,
//             currentPage: 1,
//             currentItems: 0,
//             maxSize: 5,				//max size of pagination
//             itemsPerPage: 10
//         }
//
//         $scope.getActivityList = function () {
//             var params = {
//                 userId: $scope.user.userId,
//                 pageNo: 1,
//                 pageSize: 10
//             };
//             RESTService.getResponse("/rest/useractivity/getUserActivityList?" + $.param(params)).then(function (response) {
//                 $scope.activityList = response;
//             });
//         }
//
//         $scope.getActivityList();
//
//         function User(item) {
//             var user = {
//                 userId: item.userId,
//                 realName: item.realName,
//                 mobile_Phone: item.mobile_Phone,
//                 email: item.email,
//                 icCardFile: item.icCardFile,
//                 icNo: item.icNo,
//                 gender: item.gender,
//                 race_Id: item.race_Id,
//                 age: item.age,
//                 location_Country: item.location_Country,
//                 location_Province: item.location_Province,
//                 location_City: item.location_City,
//                 location_County: item.location_County,
//                 location_Town: item.location_Town,
//                 location_Address: item.location_Address,
//                 marriage: item.marriage,
//                 telephone: item.telephone,
//                 emerg_Contact: item.emerg_Contact,
//                 emerg_Contact_Mobile: item.emerg_Contact_Mobile,
//                 photo_File: item.photo_File
//             };
//             return user;
//         };
//         function Doctor(item) {
//             var doctor = {
//                 userId: item.userId,
//                 doctQuali_Id: item.doctQuali_Id,
//                 hosp_Id: item.hosp_Id,
//                 dept_Id: item.dept_Id,
//                 doctor_Intro: item.doctor_Intro,
//                 fee_Recommend: item.fee_Recommend,
//                 fee_Diag: item.fee_Diag,
//                 fee_Solution: item.fee_Solution,
//                 cost_Surgery: item.cost_Surgery,
//                 fee_Surgery: item.fee_Surgery
//             };
//             return doctor;
//         };
//
//         //获取好友列表
//         $scope.isFriend = false;
//         $scope.userId = $scope.user.userId;
//         // console.log($scope.userIdList);
//         RESTService.getResponse("/rest/chat/getChats?").then(function(response){
//             $scope.userIdList = [];
//             angular.forEach(response,function(value){
//                 $scope.userIdList.push(value.userId);
//             });
//             if(!Array.value){
//                 if($.inArray($scope.userId,$scope.userIdList) < 0){
//                     $scope.isFriend = true;
//                 }
//             }
//             return $scope.isFriend;
//         });
//
//         //加好友
//         $scope.addFriends = function(userId){
//             $scope.friendId = userId;
//             var url = '/rest/chat/createChatMessageAddingFriend?';
//             RESTService.postResponse(url,{friendId:$scope.friendId})
//                 .then(function(response){
//                     $scope.cancel();
//                 });
//         };
//     }]);

app.controller("UserEditCtrl", ["$scope", "RESTService", "$translate",
    function ($scope, RESTService, $translate) {
        $scope.user = angular.extend({}, $scope.selected.item);

        $scope.canEditRole = false;

        //user add or edit
        $scope.hosps = [];
        $scope.depts = [];
        $scope.doctQualis = [];
        $scope.hospLevels = [];
        $scope.ArrCountry = [];
        $scope.ArrProvince = [];
        $scope.ArrCity = [];
        $scope.ArrCounty = [];

        // load data
        $scope.gender = [
            {
                value: "male",
                displayNameEn: $translate.instant('user.gender.male'),
                displayNameCn: $translate.instant('user.gender.male')
            },
            {
                value: "female",
                displayNameEn: $translate.instant('user.gender.female'),
                displayNameCn: $translate.instant('user.gender.female')
            }
        ];

        // set can edit role
        if ($scope.currentUser.isSystemAdmin || $scope.currentUser.isMedicalAdmin) {
            if ($scope.currentUser.userId != $scope.user.userId) {
                $scope.canEditRole = true;
            }
        }

        if ($scope.user.location_Country == null || $scope.user.location_Country == 0) {
            $scope.user.location_Country = 38;
        }
        if ($scope.user._doctor == null) {
            $scope.user._doctor = {
                userId: '',
                doctQuali_Id: '',
                hosp_Id: '',
                dept_Id: '',
                doctor_Intro: '',
                fee_Recommend: 0,
                fee_Diag: 0,
                fee_Solution: 0,
                cost_Surgery: 0,
                fee_Surgery: 0
            }
        }
        $scope.user._doctor.hospLevel_Id = 31;

        $scope.getHosps = function () {
            var params = {
                country_Id: $scope.user.location_Country,
                province_Id: $scope.user.location_Province,
                city_Id: $scope.user.location_City,
                county_Id: $scope.user.location_County,
                hospLevel_Id: $scope.user._doctor.hospLevel_Id,
                flag: false,
                pageNo: 1,
                pageSize: 10000
            };
            RESTService.getResponse("/rest/hosp/getHosps?" + $.param(params)).then(function (response) {
                $scope.hosps = response;
                console.log("=========$scope.hosps.length==========", $scope.hosps.length);
                if (($scope.user._doctor.hosp_Id == null || $scope.user._doctor.hosp_Id == "") && $scope.hosps.length > 0) {
                    $scope.user._doctor.hosp_Id = $scope.hosps[0].hosp_Id;
                }
            });
        }

        $scope.$watch("user.location_Country + ',' + user.location_Province + ',' + user.location_City + ',' + user.location_County + ',' + user._doctor.hospLevel_Id", function (newValue) {
            console.log("=========$watch==========", newValue);
            if (undefined !== newValue && $scope.user.isDoctor) {
                $scope.getHosps();
            }
        });

        if ($scope.user.isDoctor) {
            RESTService.getResponse("/rest/dept/getDepts?").then(function (response) {
                $scope.depts = response;
                if ($scope.user._doctor.dept_Id == null || $scope.user._doctor.dept_Id == "") {
                    $scope.user._doctor.dept_Id = $scope.depts[0].dept_Id;
                }
            });
            RESTService.getResponse("/rest/doctquali/getDoctQualis?").then(function (response) {
                $scope.doctQualis = response;
                if ($scope.user._doctor.doctQuali_Id == null || $scope.user._doctor.doctQuali_Id == "") {
                    $scope.user._doctor.doctQuali_Id = $scope.doctQualis[0].doctQuali_Id;
                }
            });
            RESTService.getResponse("/rest/hosplevel/getHospLevels?").then(function (response) {
                $scope.hospLevels = response;
            });
        }

        $scope.getCountries = function () {
            var params = {};
            RESTService.getResponse("/rest/country/getCountryList?" + $.param(params)).then(function (response) {
                if (undefined !== response) {
                    angular.forEach(response, function (arrays) {
                        $scope.ArrCountry.push(arrays);
                    });
                }
            });
        };
        $scope.getProvinces = function (flag) {
            if (flag == 1) {
                $scope.user.location_Country = 0;
                $scope.user.location_City = 0;
                $scope.user.location_County = 0;
            }
            if ($scope.user.location_Country != null && $scope.user.location_Country > 0) {
                if (gProvinces != null && gProvinces.length > 0) {
                    console.log("11111111111111111=========gProvinces==== no query db", gProvinces);
                    $scope.ArrProvince = gProvinces;
                } else {
                    console.log("11111111111111111=========gProvinces==== query db", gProvinces);
                    var params = {country_Id: $scope.user.location_Country};
                    RESTService.getResponse("/rest/location/getProvinceList?" + $.param(params)).then(function (response) {
                        if (undefined !== response) {
                            $scope.ArrProvince = response;
                            gProvinces = response;
                        }
                    });
                }
            }
        };
        $scope.getCities = function (flag) {
            if (flag == 1) {
                $scope.user.location_City = 0;
                $scope.user.location_County = 0;
            }
            if ($scope.user.location_Province != null && $scope.user.location_Province > 0) {
                var params = {province_Id: $scope.user.location_Province};
                RESTService.getResponse("/rest/location/getCityList?" + $.param(params)).then(function (response) {
                    if (undefined !== response) {
                        $scope.ArrCity = response;
                    }
                });
            }
        };
        $scope.getCounties = function (flag) {
            if (flag == 1) {
                $scope.user.location_County = 0;
            }
            if ($scope.user.location_City != null && $scope.user.location_City > 0) {
                var params = {city_Id: $scope.user.location_City};
                RESTService.getResponse("/rest/location/getCountyList?" + $.param(params)).then(function (response) {
                    if (undefined !== response) {
                        $scope.ArrCounty = response;
                    }
                });
            }
        };

        if ($scope.user.isDoctor) {
            RESTService.getResponse("/rest/doctor/getDoctor?userId=" + $scope.user.userId, true).then(function (response) {
                //$scope.doctQualis = response;
                if (response.code == 0) {
                    $scope.user._doctor.userId = response.data[0].userId;
                    $scope.user._doctor.doctQuali_Id = response.data[0].doctQuali_Id;
                    $scope.user._doctor.hosp_Id = response.data[0].hosp_Id;
                    $scope.user._doctor.dept_Id = response.data[0].dept_Id;
                    $scope.user._doctor.doctor_Intro = response.data[0].doctor_Intro;
                    $scope.user._doctor.fee_Recommend = response.data[0].fee_Recommend;
                    $scope.user._doctor.fee_Diag = response.data[0].fee_Diag;
                    $scope.user._doctor.fee_Solution = response.data[0].fee_Solution;
                    $scope.user._doctor.cost_Surgery = response.data[0].cost_Surgery;
                    $scope.user._doctor.fee_Surgery = response.data[0].fee_Surgery;
                }
            });
            $scope.getCities();
            $scope.getCounties();
        }

        $scope.userRoleKeys = [];
        $scope.userType = {
            userTypeId: $scope.selected.item.userType,
            userTypeChecked: $scope.selected.item.userType == "doctor"
        }
        $scope.userTypeId = $scope.selected.item.userType == "doctor";

        angular.forEach($scope.selected.item._userRoles, function (role) {
            $scope.userRoleKeys.push(role.key);
        });
        //user add or edit
        $scope.userRoles = [];
        RESTService.getResponse("/rest/userrole/getUserRoles?").then(function (response) {
            $scope.userRoles = response;
        });
        $scope.userTypes = [];
        RESTService.getResponse("/rest/usertype/getUserTypes?").then(function (response) {
            $scope.userTypes = response;
            if ($scope.userType.userTypeId == null && $scope.userTypes.length > 0) {
                $scope.userType.userTypeId = $scope.userTypes[0].userTypeId;
            }
            $scope.userTypeId = ($scope.userType.userTypeId == "doctor");
        });

        RESTService.getResponse("/rest/race/getRaces?").then(
            function (response) {
                $scope.races = response;
            }
        );

        function User(item) {
            var user = {
                userId: item.userId,
                realName: item.realName,
                mobile_Phone: item.mobile_Phone,
                email: item.email,
                icCardFile: item.icCardFile,
                icNo: item.icNo,
                gender: item.gender,
                race_Id: item.race_Id,
                age: item.age,
                location_Country: item.location_Country,
                location_Province: item.location_Province,
                location_City: item.location_City,
                location_County: item.location_County,
                location_Town: item.location_Town,
                location_Address: item.location_Address,
                marriage: item.marriage,
                telephone: item.telephone,
                emerg_Contact: item.emerg_Contact,
                emerg_Contact_Mobile: item.emerg_Contact_Mobile,
                photo_File: item.photo_File
            };
            return user;
        };
        function Doctor(item) {
            var doctor = {
                userId: item.userId,
                doctQuali_Id: item.doctQuali_Id,
                hosp_Id: item.hosp_Id,
                dept_Id: item.dept_Id,
                doctor_Intro: item.doctor_Intro,
                fee_Recommend: item.fee_Recommend,
                fee_Diag: item.fee_Diag,
                fee_Solution: item.fee_Solution,
                cost_Surgery: item.cost_Surgery,
                fee_Surgery: item.fee_Surgery
            };
            return doctor;
        };

        $scope.updateUser = function () {
            // transmit to server
            var vUser = User($scope.user);
            RESTService.postResponse("/rest/user/updateUser?", vUser, true)
                .then(function (response) {
                    if (response.code == 0) {
                        if (response.data[0].isDoctor && $scope.userType.userTypeChecked) {
                            var vDoctor = Doctor($scope.user._doctor);
                            RESTService.postResponse("/rest/doctor/updateDoctor?", vDoctor, true)
                                .then(function (res) {
                                    if (res.code == 0) {
                                        if ($scope.canEditRole) {
                                            $scope.updateUserRole();
                                        }
                                        else {
                                            if ($scope.user.scope) {
                                                $scope.user.scope.refreshUserListData();
                                            } else {
                                                $scope.$state.reload();
                                            }
                                            $scope.cancel();
                                        }
                                    }
                                });
                        } else {
                            if ($scope.canEditRole) {
                                $scope.updateUserRole();
                            }
                            else {
                                if ($scope.user.scope) {
                                    $scope.user.scope.refreshUserListData();
                                } else {
                                    $scope.$state.reload();
                                }
                                $scope.cancel();
                            }
                        }
                    }
                });
        }

        $scope.updateSelection = function ($event, key) {
            var checkbox = $event.target;
            if (checkbox.checked && $scope.userRoleKeys.indexOf(key) == -1) {
                $scope.userRoleKeys.push(key);
            } else if ($scope.userRoleKeys.indexOf(key) != -1) {
                var idx = $scope.userRoleKeys.indexOf(key);
                $scope.userRoleKeys.splice(idx, 1);
            }
            console.log("UserRoleCtrl --- $scope.userRoleKeys=", $scope.userRoleKeys);
        };

        $scope.updateUserRole = function () {
            var userType = $scope.userType.userTypeChecked == true ? "doctor" : "user";
            // transmit to server
            // var vUser = User($scope.user);
            // var params = "userId=" + $scope.user.userId + "&enabled=" + $scope.user.enabled + "&userRole=" + $scope.userRoleKeys + "&userType=" + userType;
            // console.log('sfa:',params);
            var userRoleDate = $scope.userRoleKeys.join(',');
            console.log('sfa:', userRoleDate);
            var params = {
                userId: $scope.user.userId,
                enabled: $scope.user.enabled,
                userRole: userRoleDate,
                userType: userType
            }
            // console.log('sfa:',params);
            RESTService.postResponse("/rest/user/updateUserRole?", params, true)
                .then(function (response) {
                    console.log('9999999:', response);
                    if (response.code == 0) {
                        //$scope.$state.reload();
                        $scope.user.scope.refreshUserListData();
                        $scope.cancel();
                    }
                });
        }
    }]);

app.controller("SystemUserOfMeController", ["$scope", "$http", "$modal", "RESTService", "AuthService",
    function ($scope, $http, $modal, RESTService, AuthService) {
        $scope.users = [];
        $scope.userRoleCnStr = "";
        $scope.userRoleEnStr = "";
        RESTService.getResponse("/rest/user/getUser?")
            .then(function (response) {
                $scope.users = response;
                console.log('asdfghjkzxcvbn',response);
                console.log('asdfghjkzxcvbn',response[0]);

                angular.forEach(response[0]._userRoles, function (role) {
                    if ($scope.userRoleCnStr != "") {
                        $scope.userRoleCnStr += ",";
                    }
                    $scope.userRoleCnStr += role.cnName;
                    if ($scope.userRoleEnStr != "") {
                        $scope.userRoleEnStr += ",";
                    }
                    $scope.userRoleEnStr += role.enName;
                });
            });

        // get head image
        /*
         ModeShapeService.getResponse("/referral/user/binary/ic/brentsun.jpg/jcr%3acontent/jcr%3adata?")
         .then(function(response) {
         $scope.userHeadImg = response;
         });
         RESTService.getResponse("/rest/filesystem/getHeadImage?")
         .then(function(response) {
         $scope.userHeadImg = response;
         });
         */

        // open modal
        $scope.open = function (attrs, model) {
            model.loginUpdated = new Date(moment(model.loginUpdated));

            var modalInstance = $modal.open(angular.extend({
                backdrop: 'static',
                controller: "ModalInstanceCtrl",
                resolve: {
                    items: function () {
                        return [Object(model)];
                    }
                }
            }, attrs));
        };

        // open upload head image window
        // entrance: openAssignSurgeon
        // call: setSurgeon(id of OCT, userId of surgeon)
        $scope.openUploadHeadImage = function (currentUser) {
            var modalInstance = $modal.open({
                backdrop: 'static',
                templateUrl: 'UploadHeadImage.html',
                controller: 'UploadHeadImageModalInstanceCtrl',
                size: 'md',
                resolve: {
                    items: function () {
                        return $scope.headImage;
                    }
                }
            });
            modalInstance.result.then(function (userId) {
                //ok click
            }, function () {
                //cancel
            });
        };

    }]);

angular.module('app').controller('UploadHeadImageModalInstanceCtrl',
    function ($scope, $http, RESTService, AuthService, $modalInstance, items) { // based on modalInstance
        $scope.ok = function () {
            $scope.uploadHeadImage(imageSrc);
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        }

        $scope.uploadHeadImage = function (imageData) {
            // alert(imageData);
            var access_token = AuthService.loadData("_access_token");
            var urladdress = AuthService.getRsContext() + "/rest/filesystem/setHeadImage?" + "&access_token=" + access_token + "";
            RESTService.postHttp(urladdress, {base64Str: imageData}).then(function (response) {
                $modalInstance.close();
            });
        };
    });

angular.module('app')
    .directive('fileModel', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs, ngModel) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;
                element.bind('change', function (event) {
                    scope.$apply(function () {
                        modelSetter(scope, element[0].files[0]);
                    });
                    scope.file = (event.srcElement || event.target).files[0];
                    scope.getFile();
                });
            }
        };
    }]);

angular.module('app')
    .controller('UploaderController', function ($scope, fileReader) {
        $scope.getFile = function () {
            fileReader.readAsDataUrl($scope.file, $scope)
                .then(function (result) {
                    $scope.imageSrc = result;
                    imageSrc = result;
                });
        };
    });

angular.module('app')
    .factory('fileReader', ["$q", "$log", function ($q, $log) {
        var dataURItoBlob = function (dataURI) {
            // convert base64/URLEncoded data component to raw binary data held in a string
            var byteString;
            if (dataURI.split(',')[0].indexOf('base64') >= 0)
                byteString = atob(dataURI.split(',')[1]);
            else
                byteString = unescape(dataURI.split(',')[1]);
            // separate out the mime component
            var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

            // write the bytes of the string to a typed array
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }

            return new Blob([ia], {
                type: mimeString
            });
        };

        var onLoad = function (reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    var img = document.createElement("img");
                    try {
                        img.src = reader.result;
                        //resize the image using canvas
                        var canvas = document.createElement("canvas");
                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(img, 0, 0);
                        var MAX_WIDTH = 1000;
                        var MAX_HEIGHT = 1000;
                        var width = img.width;
                        var height = img.height;
                        if (width > height) {
                            if (width > MAX_WIDTH) {
                                height *= MAX_WIDTH / width;
                                width = MAX_WIDTH;
                            }
                        } else {
                            if (height > MAX_HEIGHT) {
                                width *= MAX_HEIGHT / height;
                                height = MAX_HEIGHT;
                            }
                        }
                        canvas.width = width;
                        canvas.height = height;
                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(img, 0, 0, width, height);
                        //change the dataUrl to blob data for uploading to server
                        var dataURL = canvas.toDataURL('image/jpeg');
                        //var blob = dataURItoBlob(dataURL);
                        //deferred.resolve(blob);
                        console.log("old dataURL=", reader.result);	//长度 161372
                        console.log("new dataURL=", dataURL); 		//长度 38717
                        deferred.resolve(dataURL);
                    } catch (e) {
                        deferred.resolve(e);
                    }
                    /*
                     console.log("old dataURL=", reader.result);
                     deferred.resolve(reader.result);
                     */
                });
            };
        };
        var onError = function (reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.reject(reader.result);
                });
            };
        };
        var getReader = function (deferred, scope) {
            var reader = new FileReader();
            reader.onload = onLoad(reader, deferred, scope);
            reader.onerror = onError(reader, deferred, scope);
            return reader;
        };
        var readAsDataURL = function (file, scope) {
            var deferred = $q.defer();
            var reader = getReader(deferred, scope);
            reader.readAsDataURL(file);
            return deferred.promise;
        };
        return {
            readAsDataUrl: readAsDataURL
        };
    }])

            
